﻿using System;
using System.Net;



namespace Tulde.Core
{
    public static class SecurityProvider
    {
        private const string AUTH_TOKEN_FILE = "xxauthtokenxxxxx";
        private const string CREDS_FILE = "xxxcredsxxx";
        public static bool IsAuthenticated { get; private set; }
        private static bool IsRestored;
        public static ISecurityCredentials Credentials { get; private set; }
        public static IToken Token { get; private set; }
        public static event EventHandler<SecurityProviderEventArgs<ISecurityCredentials>> CredentialsChanged;
        public static event EventHandler<SecurityProviderEventArgs<IToken>> TokenChanged;

        public static void RestoreCredentials( )
        {
            if (!IsRestored)
            {
                var x = StorageProviderFactory.Instance.Read<ISecurityCredentials>(IoC.ResolveType<ISecurityCredentials>(), CREDS_FILE);
                if (x != null)
                {
                    SetCredentials(x);
                }
                Token = StorageProviderFactory.Instance.Read<IToken>(IoC.ResolveType<IToken>(), AUTH_TOKEN_FILE);
            }
            IsRestored = true;
        }
        public static void SetCredentials(ISecurityCredentials credentials)
        {
            Credentials = credentials;

            if (CredentialsChanged != null)
            {
                CredentialsChanged(null, new SecurityProviderEventArgs<ISecurityCredentials> { Source = Credentials });
            }
        }
        public static void SetAuthenticationTokens(IToken token)
        {
            Token = token;
            IsAuthenticated = true;
            SaveToken();
            if (TokenChanged != null)
            {
                TokenChanged(null, new SecurityProviderEventArgs<IToken> { Source = token });
            }
        }
        public static T LoadCredentials<T>() where T : ISecurityCredentials
        {

            return StorageProviderFactory.Instance.Read<T>(CREDS_FILE);
           
        }
        
        public static void SaveCredentials(ISecurityCredentials c)
        {
            StorageProviderFactory.Instance.Save(c.GetType(), c, CREDS_FILE);
            SaveToken();
      
        }
        private static void SaveToken( )
        {
            if (Token != null)
                StorageProviderFactory.Instance.Save(Token.GetType(),Token, AUTH_TOKEN_FILE);
        }
        public static void ClearCredentials()
        {
            StorageProviderFactory.Instance.Delete(CREDS_FILE);
            StorageProviderFactory.Instance.Delete(AUTH_TOKEN_FILE);
           
        }
    }
    public class SecurityProviderEventArgs<T> : EventArgs
    {
        public T Source { get; set; }
    }
}
